import React, { useState, useEffect } from 'react';
import axios from 'axios';

import Dhat from './Dhat';
import './Chat.css';

// Chat component for individual chat conversations

interface UserData {
  username: string;
  image: string;
  isLoggedIn: boolean;
}

interface User {
  _id: string;
  username: string;
  image: string;
}

interface ChatProps {
  currentUser: UserData;
}

const Chat: React.FC<ChatProps> = ({ currentUser }) => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [selectedUser, setSelectedUser] = useState<User | null>(null);

  // 获取用户列表（除了自己）
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        setLoading(true);
        const response = await axios.get(
          `http://localhost:3001/ysx/users?currentUser=${currentUser?.username || ''}`
        );
        if (response.data.code === 200) {
          // 过滤掉当前用户
          const filteredUsers = response.data.data.filter(
            (user: User) => user.username !== (currentUser?.username || '')
          );
          setUsers(filteredUsers);
        } else {
          setError(response.data.msg);
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        setError('获取用户列表失败');
      } finally {
        setLoading(false);
      }
    };

    if (currentUser?.username) {
      fetchUsers();
    } else {
      setLoading(false);
      setError('用户信息无效');
    }
  }, [currentUser?.username]);

  // 处理用户点击
  const handleUserClick = (user: User) => {
    console.warn('选择联系人:', user.username);
    setSelectedUser(user);
  };

  // 返回用户列表
  const handleBack = () => {
    setSelectedUser(null);
  };

  if (loading) {
    return <div className="chat-loading">加载中...</div>;
  }

  if (error) {
    return <div className="chat-error">错误: {error}</div>;
  }

  // 如果选择了用户，显示聊天界面
  if (selectedUser) {
    return (
      <Dhat
        currentUser={currentUser}
        selectedUser={selectedUser}
        onBack={handleBack}
      />
    );
  }

  // 显示用户列表
  return (
    <div className="chat-container">
      <div className="chat-header">
        <h2>选择联系人开始聊天</h2>
      </div>
      <div className="chat-users">
        {users.map(user => (
          <div
            key={user._id}
            className="chat-user-item"
            onClick={() => handleUserClick(user)}
          >
            <img
              src={user.image || '/default-avatar.png'}
              alt={user.username}
              className="chat-user-avatar"
            />
            <span className="chat-username">{user.username}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

export default Chat;
